package com.usian.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.usian.shop.utils.JWTUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author:张永杰
 * @ClassName: LoginFilter
 * @Date: 2023/12/29
 * @Description:
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求，除了不拦截登录和注册以外，所有路径都拦截
        String path = exchange.getRequest().getURI().getPath();
        System.out.println("获取到的路径为："+path);
        //判断路径是否是需要放行的请求
        if(path.contains("login")){
            return chain.filter(exchange);
        }else{
            //获取token和头信息
            String token = exchange.getRequest().getHeaders().getFirst("token");
            //从redis中获取信息
            //TODo
            if(StringUtils.isBlank(token)){
               //token无效
                ServerHttpResponse response = exchange.getResponse();
                //创建一个消息对象
                JSONObject message = new JSONObject();
                message.put("code",-1);
                message.put("errorMessage","token无效");
                //需要将提示的信息经过编码后返回前台
                byte[] bytes = message.toJSONString().getBytes(StandardCharsets.UTF_8);
                //需要将字节流放到缓冲区中
                DataBuffer buffer = response.bufferFactory().wrap(bytes);
                //将设置的编码放回response
                response.getHeaders().add("Content-Type","text/plain;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            }else{
                try {
                    //校验token是否有效
                    DecodedJWT verify = JWTUtils.verify(token);
                    String id = verify.getClaim("token").asString();
                    //将token转码
                    String username = verify.getClaim("name").asString();
                    String name = URLEncoder.encode(username, "UTF-8");
                    ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().headers(httpHeaders -> {
                        httpHeaders.add("id", id);
                        httpHeaders.add("name", name);
                    }).build();
                    exchange.mutate().request(serverHttpRequest).build();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
